package com.flyox.game.fivetiger.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.flyox.game.fivetiger.bean.MsgPackage;
import com.flyox.game.fivetiger.control.FivetigerControl;

public class DataTrafficCenter implements Runnable {

	public static final int PORT = 3721;
	private String serverIP = "127.0.0.1";

	private FivetigerControl control;
	private boolean isServer = true;
	private ServerSocket server;
	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;

	private static DataTrafficCenter serverInstance = null;
	private static DataTrafficCenter clientInstance = null;

	/**
	 * 
	 * @param isServer
	 * @param control
	 * @param serverIP
	 */
	private DataTrafficCenter(boolean isServer, FivetigerControl control, String serverIP) {
		this.isServer = isServer;
		this.control = control;
		this.serverIP = serverIP;
	}

	synchronized public static DataTrafficCenter getServerInstance(FivetigerControl control) {
		if (serverInstance == null) {
			serverInstance = new DataTrafficCenter(true, control, null);
			return serverInstance;
		} else {
			return serverInstance;
		}
	}

	synchronized public static DataTrafficCenter getClientInstance(FivetigerControl control, String serverIP) {
		if (clientInstance == null) {
			clientInstance = new DataTrafficCenter(false, control, serverIP);
			return clientInstance;
		} else {
			return clientInstance;
		}
	}

	public void run() {
		try {
			if (isServer) {
				server = new ServerSocket(PORT);
				socket = server.accept(); // 监听窗口,等待连接
			} else {
				socket = new Socket(serverIP, PORT);
			}
			// 顺序不能反
			out = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
			in = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
			
			while(socket!=null&&socket.isConnected()) {
				MsgPackage msg = (MsgPackage) in.readObject();
				control.process(msg);
			}
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			control.close();
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param msg
	 * @return
	 */
	public boolean sendMsg(MsgPackage msg) {
		try {
			if (out == null) {
				return false;
			}
			out.writeObject(msg);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		if (socket != null) {
			try{
				socket.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		if (isServer&&server!=null) {
			try{
				server.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

	public String getServerIP() {
		return serverIP;
	}

}
